#!/usr/bin/env node

/**
 * RickPan Electron开发脚本
 * 用于启动开发环境
 */

const { spawn } = require('child_process')
const { createServer } = require('vite')
const electron = require('electron')
const path = require('path')

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m'
}

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`)
}

function logStep(step, message) {
  log(`[${step}] ${message}`, 'cyan')
}

function logSuccess(message) {
  log(`✅ ${message}`, 'green')
}

function logError(message) {
  log(`❌ ${message}`, 'red')
}

class ElectronDevServer {
  constructor() {
    this.viteServer = null
    this.electronProcess = null
    this.isRestarting = false
  }

  // 启动Vite开发服务器
  async startViteServer() {
    logStep('Vite', '启动Vite开发服务器...')
    
    try {
      this.viteServer = await createServer({
        // Vite配置会自动从vite.config.ts加载
        server: {
          host: '0.0.0.0',
          port: 5173
        }
      })
      
      await this.viteServer.listen()
      
      const info = this.viteServer.config.logger.info
      info(`\n  ➜  Local:   http://localhost:5173/`)
      info(`  ➜  Network: http://0.0.0.0:5173/\n`)
      
      logSuccess('Vite开发服务器启动成功')
      
      return true
    } catch (error) {
      logError(`Vite服务器启动失败: ${error.message}`)
      return false
    }
  }

  // 启动Electron进程
  startElectronProcess() {
    if (this.isRestarting) {
      return
    }

    logStep('Electron', '启动Electron进程...')

    // Electron主进程入口
    const mainPath = path.join(process.cwd(), 'dist-electron/main.js')
    
    // 启动Electron
    this.electronProcess = spawn(electron, [mainPath], {
      stdio: 'inherit',
      env: {
        ...process.env,
        NODE_ENV: 'development'
      }
    })

    // 监听Electron进程退出
    this.electronProcess.on('close', (code) => {
      if (!this.isRestarting) {
        log(`Electron进程退出，代码: ${code}`, 'yellow')
        this.cleanup()
        process.exit(code)
      }
    })

    // 监听Electron进程错误
    this.electronProcess.on('error', (error) => {
      logError(`Electron进程错误: ${error.message}`)
    })

    logSuccess('Electron进程启动成功')
  }

  // 重启Electron进程
  restartElectronProcess() {
    if (this.isRestarting) {
      return
    }

    this.isRestarting = true
    logStep('重启', '重启Electron进程...')

    if (this.electronProcess) {
      this.electronProcess.kill()
      this.electronProcess = null
    }

    // 等待一段时间后重启
    setTimeout(() => {
      this.isRestarting = false
      this.startElectronProcess()
    }, 1000)
  }

  // 监听文件变化
  watchFiles() {
    if (!this.viteServer) {
      return
    }

    // 监听Electron主进程文件变化
    const chokidar = require('chokidar')
    
    const watcher = chokidar.watch([
      'electron/**/*.ts',
      'electron/**/*.js'
    ], {
      ignored: /node_modules/,
      persistent: true
    })

    watcher.on('change', (filePath) => {
      log(`文件变化: ${filePath}`, 'yellow')
      this.restartElectronProcess()
    })

    logSuccess('文件监听启动成功')
  }

  // 清理资源
  cleanup() {
    logStep('清理', '清理开发环境...')

    if (this.electronProcess) {
      this.electronProcess.kill()
      this.electronProcess = null
    }

    if (this.viteServer) {
      this.viteServer.close()
      this.viteServer = null
    }

    logSuccess('清理完成')
  }

  // 启动开发环境
  async start() {
    log('\n🚀 启动RickPan Electron开发环境\n', 'bright')

    // 启动Vite服务器
    const viteStarted = await this.startViteServer()
    if (!viteStarted) {
      process.exit(1)
    }

    // 等待Vite服务器完全启动
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 启动Electron进程
    this.startElectronProcess()

    // 监听文件变化
    this.watchFiles()

    // 监听进程退出信号
    process.on('SIGINT', () => {
      log('\n收到退出信号，正在清理...', 'yellow')
      this.cleanup()
      process.exit(0)
    })

    process.on('SIGTERM', () => {
      log('\n收到终止信号，正在清理...', 'yellow')
      this.cleanup()
      process.exit(0)
    })

    log('\n✨ 开发环境启动完成！\n', 'bright')
    log('提示:', 'cyan')
    log('  - Vite服务器运行在 http://localhost:5173')
    log('  - Electron应用已自动启动')
    log('  - 文件变化时会自动重启Electron')
    log('  - 按 Ctrl+C 退出开发环境\n')
  }
}

// 显示帮助信息
function showHelp() {
  log('\nRickPan Electron开发脚本\n', 'bright')
  log('用法:', 'cyan')
  log('  node scripts/dev-electron.js [选项]\n')
  log('选项:', 'cyan')
  log('  --help      显示帮助信息\n')
  log('功能:', 'cyan')
  log('  - 启动Vite开发服务器')
  log('  - 启动Electron应用')
  log('  - 监听文件变化并自动重启')
  log('  - 提供热重载功能\n')
}

// 处理命令行参数
if (process.argv.includes('--help') || process.argv.includes('-h')) {
  showHelp()
  process.exit(0)
}

// 启动开发服务器
const devServer = new ElectronDevServer()
devServer.start().catch(error => {
  logError(`启动失败: ${error.message}`)
  process.exit(1)
})
